<?php

namespace App\Api\V1\Controllers\User;

use Tiger\Api\Controllers\BaseApiController as Controller;
use Tiger\Api\Traits\RestfulFun;
use Tiger\Api\Traits\ApiResponse;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use App\Models\User;
use Tiger\Api\Traits\AuthenticatesApiUsers;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

/**
 * @SWG\Tag(
 *   name="User",
 *   description="User 模块",
 *   @SWG\ExternalDocumentation(
 *     description="Find out more",
 *     url="http://swagger.io"
 *   )
 * )
 * */
class UserController extends Controller
{
    use AuthenticatesApiUsers;
    use RestfulFun;
    use ApiResponse;




    /**
     * @SWG\Get(
     *   path="/auth/user/wechat",
     *   tags={"AuthUserController"},
     *   summary="UserController-获取微信id",
     *   description="",
     *   operationId="authUserControllerRegister",
     *   consumes={"application/x-www-form-urlencoded"},
     *   produces={ "application/json","application/xml"},
     *   @SWG\Parameter(name="name",in="query",description="用户名",required=true,type="string"),
     *   @SWG\Parameter(name="wechatcode",in="query",description="数据code",required=true,type="string"),
     *   @SWG\Response(response=200, description="successful operation", @SWG\Schema(ref="#/definitions/UserTransformer"))
     * )
     */
    public function LoginByWechat(Request $request)
    {

        $js_code =$request->input('wechatcode');

        /*            $appid = 'wx4dbc11e0aaafd25c';
                    $secret =  'cee7a3627e4c96134ab0c377fd83a651';
                    $grant_type =  'authorization_code';*/

        $appid = 'wx63cfedde1a27045a';
        $secret =  '6b914391cc9c5ef86dae649dc4b07d42';
        $grant_type =  'authorization_code';

        $user_info_url = 'https://api.weixin.qq.com/sns/jscode2session';
        $user_info_url = sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=%",$user_info_url,$appid,$secret,$js_code,$grant_type);
        $client = new Client();
        $res = $client->request('GET', $user_info_url);
        if($res->getStatusCode()!=200){
            $this->apiReturnNoPermission();
        }
        $weixin_user_data = json_decode($res->getBody());
        Log::info('log',['openid'=>$weixin_user_data->openid]);
        $openid = $weixin_user_data->openid;
        $session_key=$weixin_user_data->session_key;



        if(User::where('wechat_id',$openid)->exists())
        {
            $profile =User::where('wechatid',$openid)->first();
        }
        else {
            //  'name', 'mobile','avatar','id_number','wechat_id','birthday',
            $profile=User::create([
                'wechat_id'=>$openid,
                'name'=>$request->has('name')?$request->input('name'):str_random(10),
                'avatar'=>null,
            ]);

        }
        return $this->response->item($profile,new UserTransformer());
    }
}
